﻿define([
    "dojo/dom-attr",
    "dojo/dom-class",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/fx",
    "dojo/keys",
    "dojo/on",

    "dojo/_base/array",
    "dojo/_base/declare",
    "dojo/_base/event",
    "dojo/_base/fx",
    "dojo/_base/lang",

    "dijit/focus",
    
    "dijit",
    "dijit/_Widget",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",


    "ow-epi-tagsProperty/knockout-3.0.0",
    "ow-epi-tagsProperty/TagsViewModel",

    "dojo/text!./TreeNodeTamplate.html",

    "dojo/text!./Tags.html",
    "xstyle/css!./Tags.css"
], function (domAttr, domClass, domStyle, domConstruct, coreFx, keys, on, array, declare, event, baseFx, lang, focusUtil, dijit, _Widget, _TemplatedMixin,  _WidgetsInTemplateMixin, ko, TagsViewModel, t1, template) {
    return declare("ow-epi-tagsProperty.widgets.Tags", [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString: template,
        self: this,
        getCaretPosition: function  () {
          // Initialize
            var iCaretPos = 0;
            var oField = this.searchbox;

            // IE Support
            if (document.selection) {

                // Set focus on the element
                oField.focus ();

                // To get cursor position, get empty selection range
                var oSel = document.selection.createRange ();

                // Move selection start to 0 position
                oSel.moveStart ('character', -oField.value.length);

                // The caret position is selection length
                iCaretPos = oSel.text.length;
            }

                // Firefox support
            else if (oField.selectionStart || oField.selectionStart == '0')
                iCaretPos = oField.selectionStart;

            // Return results
            return (iCaretPos);
        },

        isValid: function () {
            return true;
        },

        postCreate: function () {
            this.inherited(arguments);

            var ref = document.getElementsByTagName("body")[0];

            domConstruct.place(t1, ref, "last");
            
            this.viewModel = new TagsViewModel(this, focusUtil, this.currentTags, this.tagsSource);

            ko.applyBindings(this.viewModel, this.widgetContainer);
        },
        
        startup: function () {
            /*self.toCleanUp = $(".to-clean");*/
        },
        
        destroy: function () {
            /*self.toCleanUp.each(function () {
               ko.cleanNode(this);
               ko.removeNode(this);
            });*/

            ko.cleanNode(this.widgetContainer);
            
            this.viewModel = null;

            this.inherited(arguments);
           
        }
    });
});